-module(p18).
-compile(export_all).

result(FileName) ->
    {ok, File} = file:open(FileName, read),
    ResList = main(File, []),
    file:close(File),
    lists:max(ResList).

main(File, List) ->
    case file:read_line(File) of
        eof -> List;
        {ok, Line} ->
            NewList = new_list(List, line_to_list(Line)),
            main(File, NewList)
    end.

line_to_list(Line) ->
    StrippedLine = string:strip(Line),
    SplitLine = re:split(StrippedLine, "\\s", [{return, list}, trim]),
    lists:map(fun erlang:list_to_integer/1, SplitLine).

new_list([], LineList) -> LineList;
new_list(OldList, LineList) -> 
    new_line_list([-1 | OldList], LineList).

new_line_list([H1], [H2]) -> [H1 + H2];
new_line_list([H1, H2 | TailOld], [Head | TailNew]) ->
    [Head + lists:max([H1, H2]) | new_line_list([H2 | TailOld], TailNew)].
    
    
